﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Write.Api.Application.Command;
using MediatR;
using SqlSugar;

namespace B.S.BaseData.Write.Api.Application.CommandHander
{
    public class AddDepmentHander : IRequestHandler<AddDepmentCommand, ApiResult<int>>
    {

        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public AddDepmentHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 部门添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddDepmentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var entity = mapper.Map<Depment>(request);
            var one = db.Queryable<Depment>().Where(x => x.DepmentName == request.DepmentName).First();

            if (one != null)
            {
                result.Code = ApiEnum.用户名不存在;
                result.Msg = ApiEnum.用户名不存在.ToString();
                result.Data = 0;
                return await Task.FromResult(result);
            }

            var list = await db.Insertable<Depment>(entity).ExecuteCommandAsync();

            if (list > 0)
            {
                result.Code = ApiEnum.添加成功;
                result.Msg = ApiEnum.添加成功.ToString();
                result.Data = list;
            }
            else
            {
                result.Code = ApiEnum.添加失败;
                result.Msg = ApiEnum.添加失败.ToString();
                result.Data = list;
            }

            return await Task.FromResult(result);
        }
    }
}
